import 'package:flutter/material.dart';
import '../models/user.dart';
import 'package:http/http.dart' as http; // 添加http包
import 'dart:convert'; // 用于JSON解析
import 'api_service.dart';
// import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class AuthService with ChangeNotifier {
  User? _currentUser;
  bool _isAuthenticated = false;
  String?  _accessToken; // 添加token存储

  User? get currentUser => _currentUser;
  bool get isAuthenticated => _isAuthenticated;
  String? get accessToken => _accessToken;

  Future<Map<String,dynamic>> login(BuildContext context,String username, String password) async {

    // 1. 创建API请求URL（替换为你的实际API地址）
    final url = ApiService.baseURL + ApiService.login;
    try {
      // 2. 发送POST请求
      final response = await http.post(
        Uri.parse(url),
        body: jsonEncode({
          'username': username,
          'password': password,
        }),
        headers: {
          'Content-Type': 'application/json',
          'X-Client-Type': 'app',
        },
      ).timeout(Duration(seconds: 10));
      // 3. 检查HTTP状态码
      if (response.statusCode == 200) {
        Map<String, dynamic> jsonData = json.decode(response.body);
        if(jsonData['code'] == 2000){
          _isAuthenticated = true;
          _accessToken = jsonData['data']['access']; // 存储access token
          print('jsonData----:${jsonData}');
          print('_accessToken----:${_accessToken}');
          // 4. 解析响应数据
          // 修复 warehouse 处理逻辑
          dynamic warehouseData = jsonData['data']?['warehouse'];
          int? warehouseId;
          
          if (warehouseData is List && warehouseData.isNotEmpty) {
            warehouseId = warehouseData[0]['id'];
          }
          // 5. 根据API响应结构处理数据（示例结构）
          _currentUser = User(
            username: jsonData['data']?['username'],
            name: jsonData['data']?['name'],
            avatar: jsonData['data']?['avatar'],
            pwdChangeCount: jsonData['data']?['pwd_change_count'],
            roleInfo: jsonData['data']?['role_info'],
            userId: jsonData['data']?['userId'],
            warehouse: warehouseId,
          );
          
          notifyListeners();
          return jsonData;
        }
        else{
          throw Exception(jsonData['msg']);
        }
      } else {
        // 处理非200状态码
        _isAuthenticated = false;
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      // 6. 统一错误处理
      // _accessToken = null;
      notifyListeners();
      throw Exception('${e.toString()}');
    }
  }

  Future<void> logout(BuildContext context) async {

    // // 清除安全存储中的凭证
    // const storage = FlutterSecureStorage();
    // await storage.delete(key: 'username');
    // await storage.delete(key: 'password');

    _currentUser = null;
    _isAuthenticated = false;
    _accessToken = null;
    notifyListeners();

    // 重置路由栈
    Navigator.of(context).pushNamedAndRemoveUntil(
      '/login',
      (Route<dynamic> route) => false
    );
  }
}